// 病友圈主页面组件



/**
 * 病友圈主页面组件
 * 包含科室列表展示、病友圈内容展示、搜索功能等
 */
import { useEffect, useState } from 'react';
import axios from '../../request/axios';
import { List, Spin, Empty, Alert, Tabs, Input, Typography } from 'antd';
import { useNavigate } from "react-router-dom";
import { NavBar } from 'react-vant';

const { TabPane } = Tabs;
const { Search } = Input;
const { Title } = Typography;

/**
 * 科室信息接口
 */
interface Department {
    id: number;
    departmentName: string;
}

/**
 * 病友圈信息接口
 */
interface SickCircle {
    id: number;
    title: string;
    detail: string;
    releaseTime: string;
    collectionNum: number;
    commentNum: number;
    amount: number;
}

/**
 * 防抖函数
 * @param func 需要执行的函数
 * @param wait 等待时间（毫秒）
 * @returns 返回一个防抖处理后的函数
 */
const debounce = (func: (...args: any[]) => void, wait: number) => {
    let timeout: ReturnType<typeof setTimeout>;
    return function executedFunction(...args: any[]) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

function Index() {
    // 状态管理
    const [data, setData] = useState<SickCircle[]>([]); // 病友圈数据列表
    const [departments, setDepartments] = useState<Department[]>([]); // 科室列表
    const [loading, setLoading] = useState(true); // 主数据加载状态
    const [deptLoading, setDeptLoading] = useState(true); // 科室加载状态
    const [error, setError] = useState<string | null>(null); // 错误信息
    const [activeDept, setActiveDept] = useState<number | null>(null); // 当前选中的科室ID
    const [searchResults, setSearchResults] = useState<SickCircle[] | null>(null); // 搜索结果
    const [searchLoading, setSearchLoading] = useState(false); // 搜索加载状态
    const [searchValue, setSearchValue] = useState(''); // 搜索关键词
    const [page, setPage] = useState(1); // 当前页码
    const [hasMore, setHasMore] = useState(true); // 是否还有更多数据
    const [loadingMore, setLoadingMore] = useState(false); // 加载更多状态
    const navigate = useNavigate();

    /**
     * 获取科室列表数据
     * 从服务器获取所有科室信息并设置默认选中第一个科室
     */
    const fetchDepartments = () => {
        setDeptLoading(true);
        axios({
            url: '/health/share/knowledgeBase/v1/findDepartment',
            method: 'get'
        })
            .then(res => {
                console.log(res);
                const deptData = res.data.result || [];
                setDepartments(deptData);
                if (deptData.length > 0) {
                    setActiveDept(deptData[0].id);
                }
            })
            .catch(err => {
                console.error('科室加载错误:', err);
                setError('科室列表加载失败');
            })
            .finally(() => {
                setDeptLoading(false);
            });
    };

    /**
     * 获取病友圈数据
     * @param departmentId 科室ID
     * @param isLoadMore 是否为加载更多操作
     */
    const fetchData = (departmentId: number, isLoadMore = false) => {
        if (!departmentId || (isLoadMore && !hasMore)) return;

        const loadingState = isLoadMore ? setLoadingMore : setLoading;
        loadingState(true);
        setError(null);

        axios({
            url: '/health/user/sickCircle/v1/findSickCircleList',
            method: 'get',
            params: {
                departmentId: departmentId,
                page: isLoadMore ? page + 1 : 1,
                count: 10
            }
        })
            .then(res => {
                const resultData = res.data.result?.list ||
                    res.data.result ||
                    res.data.data ||
                    [];

                if (resultData.length === 0) {
                    if (isLoadMore) {
                        setHasMore(false);
                    } else {
                        setError('当前科室暂无病友圈数据');
                    }
                }

                if (isLoadMore) {
                    setData(prev => [...prev, ...resultData]);
                    setPage(prev => prev + 1);
                } else {
                    setData(resultData);
                    setPage(1);
                    setHasMore(true);
                }
            })
            .catch(err => {
                console.error('API错误:', err);
                setError(err.response?.data?.message || '请求数据失败');
            })
            .finally(() => {
                loadingState(false);
            });
    };

    /**
     * 搜索病友圈功能
     * @param value 搜索关键词
     */
    const handleSearch = (value: string) => {
        if (!value.trim()) {
            setSearchResults(null);
            setSearchValue('');
            return;
        }

        setSearchValue(value);
        setSearchLoading(true);
        setError(null);

        axios({
            url: '/health/user/sickCircle/v1/searchSickCircle',
            method: 'get',
            params: {
                keyWord: value
            }
        }).then(res => {
            const resultData = res.data.result || [];
            setSearchResults(resultData);

            if (resultData.length === 0) {
                setError('没有找到相关的病友圈');
            }
        })
            .catch(err => {
                console.error('搜索错误:', err);
                setError(err.response?.data?.message || '搜索失败');
            })
            .finally(() => {
                setSearchLoading(false);
            });
    };

    /**
     * 处理科室切换
     * @param activeKey 选中的科室ID
     */
    const handleTabChange = (activeKey: string) => {
        const deptId = parseInt(activeKey, 10);
        setActiveDept(deptId);
        setSearchResults(null);
        setSearchValue('');
        fetchData(deptId);
    };

    /**
     * 格式化时间戳为可读时间
     * @param timestamp 时间戳字符串
     * @returns 格式化后的时间字符串
     */
    const formatTime = (timestamp: string) => {
        if (!timestamp) return '未知时间';
        const date = new Date(timestamp);
        return date.toLocaleString();
    };

    /**
     * 处理病友圈点击事件
     * @param id 病友圈ID
     */
    const handleSickCircleClick = (id: number) => {
        console.log(id, 123444444444444);
        navigate(`/moments/detail/${id}`);
    };

    // 监听滚动事件，实现无限加载
    useEffect(() => {
        const handleScroll = debounce(() => {
            if (searchResults || loading || loadingMore || !hasMore) return;

            const scrollHeight = document.documentElement.scrollHeight;
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            const clientHeight = document.documentElement.clientHeight;

            if (scrollTop + clientHeight >= scrollHeight - 100) {
                fetchData(activeDept!, true);
            }
        }, 200);
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, [activeDept, hasMore, loading, loadingMore, searchResults]);

    // 组件挂载时获取科室列表
    useEffect(() => {
        fetchDepartments();
    }, []);

    // 当选中科室变化时，获取对应的病友圈数据
    useEffect(() => {
        if (activeDept) {
            fetchData(activeDept);
        }
    }, [activeDept]);

    return (
        <div className="by-container">
            {/* 顶部导航栏 */}
            <NavBar
                title="病友圈"
                leftText="返回"
                onClickLeft={() => navigate('/home')}
            />

            {/* 搜索框组件 */}
            <div className="search-container">
                <Search
                    placeholder="搜索病友圈内容"
                    allowClear
                    enterButton="搜索"
                    size="large"
                    onSearch={handleSearch}
                    loading={searchLoading}
                    value={searchValue}
                    onChange={(e) => setSearchValue(e.target.value)}
                />
            </div>

            {/* 搜索结果展示区域 */}
            {searchResults && (
                <div className="search-results">
                    <Title level={4} className="search-title">搜索结果</Title>

                    {error ? (
                        <Alert
                            message="搜索失败"
                            description={error}
                            type="error"
                            showIcon
                            action={
                                <button
                                    className="reload-button"
                                    onClick={() => handleSearch(searchValue)}
                                >
                                    重新搜索
                                </button>
                            }
                        />
                    ) : searchLoading ? (
                        <Spin tip="搜索中..." size="large" />
                    ) : searchResults.length === 0 ? (
                        <Empty
                            description="没有找到相关的病友圈"
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                        />
                    ) : (
                        <List
                            dataSource={searchResults}
                            renderItem={item => (
                                <List.Item
                                    className="list-item"
                                    extra={
                                        <div className="item-stats">
                                            <span>收藏: {item.collectionNum || 0}</span>
                                            <span>评论: {item.commentNum || 0}</span>
                                            {item.amount > 0 && <span className="reward">悬赏: {item.amount}</span>}
                                        </div>
                                    }
                                >
                                    <List.Item.Meta
                                        title={<span>{item.title || '未命名'}</span>}
                                        description={
                                            <>
                                                <div>{item.detail || '暂无内容描述'}</div>
                                                <div className="list-item-time">
                                                    {formatTime(item.releaseTime)}
                                                </div>
                                            </>
                                        }
                                    />
                                </List.Item>
                            )}
                        />
                    )}
                </div>
            )}

            {/* 原始病友圈内容展示区域 */}
            {!searchResults && (
                <>
                    {deptLoading ? (
                        <Spin tip="加载科室..." size="large" />
                    ) : departments.length > 0 ? (
                        <Tabs
                            activeKey={String(activeDept)}
                            onChange={handleTabChange}
                            tabPosition="top"
                            type="card"
                        >
                            {departments.map(dept => (
                                <TabPane
                                    tab={dept.departmentName}
                                    key={String(dept.id)}
                                >
                                    {error ? (
                                        <Alert
                                            message="加载失败"
                                            description={error}
                                            type="error"
                                            showIcon
                                            action={
                                                <button
                                                    className="reload-button"
                                                    onClick={() => fetchData(activeDept!)}
                                                >
                                                    重新加载
                                                </button>
                                            }
                                        />
                                    ) : loading ? (
                                        <Spin tip="加载中..." size="large" />
                                    ) : data.length === 0 ? (
                                        <Empty
                                            description="暂无病友圈数据"
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        />
                                    ) : (
                                        <List
                                            dataSource={data}
                                            renderItem={item => (
                                                <List.Item
                                                    className="list-item"
                                                    onClick={() => handleSickCircleClick(item.sickCircleId)}
                                                    style={{ cursor: 'pointer' }}
                                                    extra={
                                                        <div className="item-stats">
                                                            <span>收藏: {item.collectionNum || 0}</span>
                                                            <span>评论: {item.commentNum || 0}</span>
                                                            {item.amount > 0 && <span className="reward">悬赏: {item.amount}</span>}
                                                        </div>
                                                    }
                                                >
                                                    <List.Item.Meta
                                                        title={<h3>{item.title || '未命名'}</h3>}
                                                        description={
                                                            <>
                                                                <div>{item.detail || '暂无内容描述'}</div>
                                                                <div className="list-item-time">
                                                                    {formatTime(item.releaseTime)}
                                                                </div>
                                                            </>
                                                        }
                                                    />
                                                </List.Item>
                                            )}
                                            footer={
                                                loadingMore ? (
                                                    <div className="load-more-container">
                                                        <Spin className="load-more-spinner" size="small" />
                                                        <span>正在加载更多...</span>
                                                    </div>
                                                ) : !hasMore && data.length > 0 ? (
                                                    <div className="no-more-data">已经到底了，没有更多数据了</div>
                                                ) : null
                                            }
                                        />
                                    )}
                                </TabPane>
                            ))}
                        </Tabs>
                    ) : (
                        <Empty description="暂无科室数据" />
                    )}
                </>
            )}
        </div>
    );
}

export default Index;